package com.geqian.file.storage;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.UUID;

/**
 * @author geqian
 * @date 0:52 2024/1/5
 */
public class AliyunOSSStorage implements FileStorageTemplate {

    @Resource
    private OSSClient ossClient;

    @Value("${alibaba.cloud.oss.bucket}")
    private String bucketName;

    @Value("${alibaba.cloud.oss.file.expiration-days:30}")
    private int expirationDays;

    //日期格式转换
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    @Override
    public String uploadFile(byte[] bytes, String filename) {
        String objectName = generateObjectName(filename);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(bytes));
        ossClient.putObject(putObjectRequest);
        return generateUrl(objectName, expirationDays);
    }

    /**
     * 上传文件
     *
     * @param inputStream 输入流
     * @param filename    文件名称
     */
    @Override
    public String uploadFile(InputStream inputStream, String filename) {
        String objectName = generateObjectName(filename);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
        ossClient.putObject(putObjectRequest);
        return generateUrl(objectName, expirationDays);
    }


    @Override
    public void deleteFile(String url) {
        String objectName = url.replaceFirst("^.*//.*aliyuncs.com/", "").replaceFirst("\\?.*", "");
        ossClient.deleteObject(bucketName, objectName);
    }



    /**
     * uuid生成文件名，并将文件上传日期作为文件目录，拼接到文件名上
     *
     * @param filename
     * @return
     */
    private String generateObjectName(String filename) {
        String directory = dateTimeFormatter.format(LocalDateTime.now()) + "/";
        filename = UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf("."));
        return directory + filename;
    }


    /**
     * 生成文件的URL
     *
     * @param objectName 文件名称
     * @return 文件URL
     */
    private String generateUrl(String objectName, int expirationDays) {
        // 设置 URL 过期时间为一个月
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, expirationDays);
        // 生成带有签名的文件访问 URL
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
        generatePresignedUrlRequest.setExpiration(calendar.getTime());
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

}
